package com.aliyun.heiyu.powermaster.server;

import com.aliyun.heiyu.common.util.*;
import com.aliyun.heiyu.powermaster.proto.*;
import com.aliyun.heiyu.powermaster.server.dao.enums.DeviceErrorEnum;
import com.aliyun.heiyu.powermaster.server.dao.enums.UserErrorEnum;
import com.aliyun.heiyu.powermaster.server.database.OperaService;
import com.aliyun.heiyu.powermaster.server.database.OperaServiceImpl;
import com.aliyun.heiyu.powermaster.server.manager.StrategyManager;
import com.aliyun.heiyu.powermaster.server.manager.ThunderManager;
import com.aliyun.heiyu.powermaster.server.manager.ThunderManagerImpl;
import com.aliyun.heiyu.powermaster.server.market.K8sManager;
import com.aliyun.heiyu.powermaster.server.rbac.dao.TokenMangerDao;
import com.aliyun.heiyu.powermaster.server.rbac.dao.impl.TokenMangerDaoImpl;
import com.aliyun.heiyu.powermaster.server.rbac.object.entity.SysSafeAuditEntity;
import com.aliyun.heiyu.powermaster.server.rbac.service.SafeService;
import com.aliyun.heiyu.powermaster.server.rbac.service.SysAuditManagementsService;
import com.aliyun.heiyu.powermaster.server.rbac.service.SysAuditManagementsServiceImpl;
import com.aliyun.heiyu.powermaster.server.rbac.service.impl.SafeServiceImpl;
import com.aliyun.heiyu.powermaster.server.rbac.service.impl.TokenManagerImpl;
import com.aliyun.heiyu.powermaster.server.rotary.service.*;
import com.aliyun.heiyu.powermaster.server.rotary.service.impl.*;
import com.aliyun.heiyu.powermaster.server.rotary.task.Task;
import com.aliyun.heiyu.powermaster.server.service.*;
import com.aliyun.heiyu.powermaster.server.util.ZkClientUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import io.grpc.stub.StreamObserver;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.*;
/**
 * Provide administration control to PowerMaster server
 */
class PowerMasterServiceImpl extends PowerMasterServiceGrpc.PowerMasterServiceImplBase {
    private static Logger logger = LoggerFactory.getLogger(PowerMasterServiceImpl.class);

    private StrategyService strategyService;
    private StrategyManager strategyManager;
    private WarningService warningService;
    private PowerDataService powerDataService;
    private AiDataProvider aiDataProvider;
    private ThunderManager thunderDataProvider;
    private ZkServerThread zkStart;
    private ZookeeperProvider zookeeperProvider;
    private AirService airService;
    private WarnService warnService;
    private ServerService serverService;
    private AlgorithmService algorithmService;
    private EnergyViewProvider energyViewProvider;
    private OperaService operaService;
    private SafeService safeService;
    private PropertiesService propertiesService;
    private TokenManagerImpl tokenManager;
    private CfdService cfdService;
    private SysAuditManagementsService auditManagementsService;
    private TokenMangerDao tokenMangerDao;
    private K8sManager k8sManager;
    private ZkMonitorInIt zkMonitorInIt;
    private boolean zkSwitch = Boolean.valueOf(PropertiesUtil.getValue("serverIp.properties", "zkSwitch"));

    public PowerMasterServiceImpl() {
        if(zkSwitch) {
            this.zkStart = new ZkServerThread();
            try {
                Thread.sleep(5000L);
            } catch (InterruptedException e) {
                logger.error(e.getMessage());
            }
        }
        if(zkSwitch) {
            this.zookeeperProvider = new ZookeeperProviderImpl();
        }
        this.strategyService = new StrategyServiceImpl();
        this.strategyManager = StrategyManager.getInstance();
        this.warningService = new WarningServiceImpl();
        this.powerDataService = new PowerDataServiceImpl();
        this.aiDataProvider = new AiDataProviderImpl();
        this.thunderDataProvider = new ThunderManagerImpl();
        this.energyViewProvider = new EnergyViewProviderImpl();
        this.propertiesService = PropertiesServiceImpl.getInstance();
        this.airService = new AirServiceImpl();
        this.warnService = new WarnServiceImpl(1);
        this.serverService = new ServerServiceImpl(1);
        this.operaService = new OperaServiceImpl();
        this.algorithmService = new AlgorithmServiceImpl();
        this.safeService = new SafeServiceImpl();
        this.tokenManager = new TokenManagerImpl();
        this.cfdService = new CfdServiceImpl();
        this.tokenMangerDao = new TokenMangerDaoImpl();
        k8sManager = new K8sManager();
        this.auditManagementsService = new SysAuditManagementsServiceImpl();
        if(zkSwitch) {
            this.zkMonitorInIt = ZkMonitorInIt.getInstance();
        }
        new Task();
    }
    /**
     * <pre>
     * 算法模块
     * 1.算法列表
     * </pre>
     */
    @Override
    public void queryAlgorithms(AlgorithmsRequest request,
                                StreamObserver<AlgorithmsReply> responseObserver) {
        AlgorithmsReply.Builder builder = AlgorithmsReply.newBuilder();
        AlgorithmsReply reply;
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "z")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/algorithm/list}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), request.getToken());
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = algorithmService.queryAlgorithms(request);

                List<Algorithm> dataList = reply.getDataList();
                int total = dataList.size();
                Map<Integer, List<Algorithm>> pageNum2Content = getCurrentPageNum2Content(dataList, request.getPageSize(), request.getPageNum());

                int pageNum = 0;
                List<Algorithm> pageContent = new ArrayList<>();
                for (Integer key : pageNum2Content.keySet()) {
                    pageNum = key;
                    pageContent = pageNum2Content.get(key);
                }
                builder.addAllData(pageContent);
                builder.setErrCode(Error.SUCCESS.getCode()).setErrMsg(Error.SUCCESS.getMessage());
                builder.setTotal(total);
                builder.setCurrentPage(pageNum);
                reply = builder.build();
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            builder.setErrCode(Error.FAILED.getCode());
            builder.setErrMsg(Error.FAILED.getMessage());
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
        }
    }
    /**
     * <pre>
     * 4.查询算法详情
     * </pre>
     */
    //20版本前后端交互没用到
    @Override
    public void queryAlgorithmById(AlgorithmRequest request,
                                   StreamObserver<AlgorithmReply> responseObserver) {
        AlgorithmReply.Builder builder = AlgorithmReply.newBuilder();
        AlgorithmReply reply;
        try {
            reply = algorithmService.queryAlgorithmById(request);
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            builder.setErrCode(Error.FAILED.getCode());
            builder.setErrMsg(Error.FAILED.getMessage());
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
        }
    }

    /**
     * <pre>
     * 5.修改算法
     * </pre>
     */
    @Override
    public void updateAlgorithmById(AlgorithmRequest request,
                                    StreamObserver<CommonReply> responseObserver) {
        CommonReply.Builder builder = CommonReply.newBuilder();
        CommonReply reply;
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "z")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/algorithm/update}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), request.getToken());
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = algorithmService.updateAlgorithm(request);
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            builder.setErrCode(Error.FAILED.getCode());
            builder.setErrMsg(Error.FAILED.getMessage());
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
        }
    }

    /**
     * <pre>
     * 6.删除算法
     * </pre>
     */
    @Override
    public void deleteAlgorithmById(AlgorithmRequest request,
                                    StreamObserver<CommonReply> responseObserver) {
        CommonReply.Builder builder = CommonReply.newBuilder();
        CommonReply reply;
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "z")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/algorithm/delete}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), request.getToken());
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = algorithmService.deleteAlgorithm(request);
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            builder.setErrCode(Error.FAILED.getCode());
            builder.setErrMsg(Error.FAILED.getMessage());
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
        }
    }

    /**
     * <pre>
     * 7.添加算法
     * </pre>
     */
    @Override
    public void addAlgorithm(AlgorithmRequest request,
                             StreamObserver<CommonReply> responseObserver) {
        CommonReply.Builder builder = CommonReply.newBuilder();
        CommonReply reply;
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "z")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/algorithm/add}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), request.getToken());
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = algorithmService.addAlgorithm(request);
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            builder.setErrCode(Error.FAILED.getCode());
            builder.setErrMsg(Error.FAILED.getMessage());
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
        }
    }

    /**
     * <pre>
     * 8.算法开关
     * </pre>
     */
    @Override
    public void updateAlgorithmSwitch(AlgorithmRequest request,
                                      StreamObserver<CommonReply> responseObserver) {
        CommonReply.Builder builder = CommonReply.newBuilder();
        CommonReply reply;
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "z")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/algorithm/switch}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), request.getToken());
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = algorithmService.updateAlgorithmSwitch(request);
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            builder.setErrCode(Error.FAILED.getCode());
            builder.setErrMsg(Error.FAILED.getMessage());
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
        }
    }

//   数据日志   获取日志信息
    @Override
    public void getLogMassage(GetLogMassageRequest request, StreamObserver<GetLogMassageReply> responseObserver) {
        GetLogMassageReply.Builder builder = GetLogMassageReply.newBuilder();
        GetLogMassageReply reply;
        try {
            String token = request.getToken();
            int code = tokenManager.checkToken(token);
            if (code != 0) {

                reply = builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg()).build();
            } else if (!validation(token, "t")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/properties/logMassage}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                List<LogMassage> list = propertiesService.findLogByCondition(request);
                if (!ObjectUtils.isEmpty(list)) {
                    GetLogMassageReply.Data.Builder builder1 = GetLogMassageReply.Data.newBuilder();
                    int total = list.size();
                    if (request.getPageSize() == -1) {
                        builder1.addAllLogMassage(list);
                        builder.setData(builder1.build());
                    } else {
                        Map<Integer, List<LogMassage>> pageNum2Content = getCurrentPageNum2Content(list, request.getPageSize(), request.getPageNum());
                        int pageNum = 0;
                        List<LogMassage> pageContent = null;
                        for (Integer key : pageNum2Content.keySet()) {
                            pageNum = key;
                            pageContent = pageNum2Content.get(key);
                        }
                        if(pageContent != null){
                            builder1.addAllLogMassage(pageContent);
                        }
                        builder.setData(builder1.build());
                        builder.setCurrentPage(pageNum);
                    }
                    builder.setTotal(total);
                }
                reply = builder.build();
            }
            builder.setErrCode(Error.SUCCESS.getCode()).setErrMsg(Error.SUCCESS.getMessage());
        } catch (Exception e) {
            reply = builder.setErrCode(DeviceErrorEnum.SYSTEM_ERROR.getCode()).setErrMsg(DeviceErrorEnum.SYSTEM_ERROR.getMsg()).build();
            logger.error(e.getMessage(), e);
        }
        responseObserver.onNext(reply);
        responseObserver.onCompleted();
    }

    @Override
    public void getLogHistory(GetLogHistoryRequest request, StreamObserver<GetLogHistoryReply> responseObserver) {
        GetLogHistoryReply.Builder builder = GetLogHistoryReply.newBuilder();
        GetLogHistoryReply reply;
        try {
            String token = request.getToken();
            int code = tokenManager.checkToken(token);
            if (code != 0) {

                reply = builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg()).build();
            } else if (!validation(token, "w")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/properties/logHistory}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                List<UpdateLogRequest> list = propertiesService.getLogHistory(request);
                if (!ObjectUtils.isEmpty(list)) {
                    int total = list.size();
                    Map<Integer, List<UpdateLogRequest>> pageNum2Content = getCurrentPageNum2Content(list, request.getPageSize(), request.getPageNum());
                    int pageNum = 0;
                    List<UpdateLogRequest> pageContent = null;
                    for (Integer key : pageNum2Content.keySet()) {
                        pageNum = key;
                        pageContent = pageNum2Content.get(key);
                    }
                    GetLogHistoryReply.Data.Builder builder1 = GetLogHistoryReply.Data.newBuilder();
                    if(pageContent != null){
                        builder1.addAllLogHistory(pageContent);
                    }
                    builder.setData(builder1.build());
                    builder.setTotal(total);
                    builder.setCurrentPage(pageNum);
                }
                reply = builder.build();
            }
            builder.setErrCode(Error.SUCCESS.getCode()).setErrMsg(Error.SUCCESS.getMessage());
        } catch (Exception e) {
            reply = builder.setErrCode(DeviceErrorEnum.SYSTEM_ERROR.getCode()).setErrMsg(DeviceErrorEnum.SYSTEM_ERROR.getMsg()).build();
            logger.error(e.getMessage(), e);
        }
        responseObserver.onNext(reply);
        responseObserver.onCompleted();
    }
    //数据库备份
    @Override
    public void databaseBackup(DatabaseBackupRequest request, StreamObserver<DatabaseBackupReply> responseObserver) {
        DatabaseBackupReply.Builder builder = DatabaseBackupReply.newBuilder();
        DatabaseBackupReply reply;
        try {
            String token = request.getToken();
            int code = tokenManager.checkToken(token);
            if (code != 0) {

                reply = builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg()).build();
            } else if (!validation(token, "q")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/properties/database}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                String s = propertiesService.databaseBackup();
                reply = builder.setData(s).setErrCode(Error.SUCCESS.getCode()).setErrMsg(Error.SUCCESS.getMessage()).build();
            }
        } catch (Exception e) {
            reply = builder.setErrCode(DeviceErrorEnum.SYSTEM_ERROR.getCode()).setErrMsg(DeviceErrorEnum.SYSTEM_ERROR.getMsg()).build();
            logger.error(e.getMessage(), e);
        }
        responseObserver.onNext(reply);
        responseObserver.onCompleted();
    }
    @Override
    public void getUserList(SafeUserRequest request, StreamObserver<SafeUserReply> responseObserver) {
        SafeUserReply.Builder builder = SafeUserReply.newBuilder();
        SafeUserReply reply;
        try {
            String token = request.getToken();
            StringBuilder str = new StringBuilder();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "l")) {
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/safe/userList}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), request.getToken());
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                List<Map<String, String>> allUser = tokenMangerDao.findAllUser();
                SafeUserReply.Builder builder1 = SafeUserReply.newBuilder();
                if (!ObjectUtils.isEmpty(allUser)) {
                    for (Map<String, String> map : allUser) {
                        SafeUser.Builder builder2 = SafeUser.newBuilder();
                        builder2.setUserId(map.get("id"));
                        builder2.setUsername(new SM4JSUtil().decode(map.get("data")));
                        builder1.addData(builder2);
                    }
                }
                reply = builder1.setErrCode(Error.SUCCESS.getCode()).setErrMsg(Error.SUCCESS.getMessage()).build();
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            reply = builder.setErrCode(DeviceErrorEnum.SYSTEM_ERROR.getCode()).setErrMsg(DeviceErrorEnum.SYSTEM_ERROR.getMsg()).build();
            logger.error(e.getMessage(), e);
        }
        responseObserver.onNext(reply);
        responseObserver.onCompleted();
    }

    @Override
    public void findSafeCapacity(FindSafeCapacityRequest request, StreamObserver<FindSafeCapacityReply> responseObserver) {
        FindSafeCapacityReply.Builder builder = FindSafeCapacityReply.newBuilder();
        FindSafeCapacityReply reply;
        try {
            String token = request.getToken();
            int code = tokenManager.checkToken(token);
            if (code != 0) {
                reply = builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg()).build();
            }  else if (!validation(token, "i")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/safe/findCapacity}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = safeService.findSafeCapacity(request);
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            reply = builder.setErrCode(DeviceErrorEnum.SYSTEM_ERROR.getCode()).setErrMsg(DeviceErrorEnum.SYSTEM_ERROR.getMsg()).build();
            logger.error(e.getMessage(), e);
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }
    }

    @Override
    public void updateSafeCapacity(UpdateSafeCapacityRequest request, StreamObserver<UpdateSafeCapacityReply> responseObserver) {
        UpdateSafeCapacityReply.Builder builder = UpdateSafeCapacityReply.newBuilder();
        UpdateSafeCapacityReply reply;
        try {
            String token = request.getToken();
            int code = tokenManager.checkToken(token);
            if (code != 0) {
                reply = builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg()).build();
            }  else if (!validation(token, "i")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/safe/updateCapacity}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = safeService.updateSafeCapacity(request);
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            reply = builder.setErrCode(DeviceErrorEnum.SYSTEM_ERROR.getCode()).setErrMsg(DeviceErrorEnum.SYSTEM_ERROR.getMsg()).build();
            logger.error(e.getMessage(), e);
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }
    }
    /**
     * 添加策略管理
     * @param request
     * @param responseObserver
     */
    @Override
    public void saveAuditManagement(AuditManagementRequest request, StreamObserver<AuditManagementReply> responseObserver) {
        AuditManagementReply.Builder builder = AuditManagementReply.newBuilder();
        AuditManagementReply reply;
        try{
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "l")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/audit/saveAuditManagement}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), request.getToken());
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = auditManagementsService.saveAuditManagement(request);
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }catch (Exception e){
            logger.error(e.getMessage(), e);
            builder.setErrCode(Error.FAILED.getCode())
                .setErrMsg(Error.FAILED.getMessage());
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
        }

    }

    /**
     * 更新策略管理
     * @param request
     * @param responseObserver
     */
    @Override
    public void updateAuditManagement(AuditManagementRequest request, StreamObserver<AuditManagementReply> responseObserver) {
        AuditManagementReply.Builder builder = AuditManagementReply.newBuilder();
        AuditManagementReply reply;
        try{
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "l")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/audit/updateAuditManagement}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), request.getToken());
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = auditManagementsService.updateAuditManagement(request);
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }catch (Exception e){
            logger.error(e.getMessage(), e);
            builder.setErrCode(Error.FAILED.getCode())
                .setErrMsg(Error.FAILED.getMessage());
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
        }
    }

    /**
     * 删除策略管理
     * @param request
     * @param responseObserver
     */
    @Override
    public void deleteAuditManagement(AuditManagementRequest request, StreamObserver<AuditManagementReply> responseObserver) {
        AuditManagementReply.Builder builder = AuditManagementReply.newBuilder();
        AuditManagementReply reply;
        try{
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "l")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/audit/deleteAuditManagement}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), request.getToken());
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = auditManagementsService.deleteAuditManagement(request.getId());
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }catch (Exception e){
            logger.error(e.getMessage(), e);
            builder.setErrCode(Error.FAILED.getCode())
                .setErrMsg(Error.FAILED.getMessage());
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
        }


    }

    /**
     * 获取策略管理列表
     * @param request
     * @param responseObserver
     */
    @Override
    public void getAuditManagements(AuditManagementRequest request, StreamObserver<AuditManagementQueryReply> responseObserver) {
        AuditManagementQueryReply.Builder builder = AuditManagementQueryReply.newBuilder();
        AuditManagementQueryReply reply;
        try{
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "l")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/audit/getAuditManagements}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), request.getToken());
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = auditManagementsService.getAuditManagements(request);
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }catch (Exception e){
            logger.error(e.getMessage(), e);
            builder.setErrCode(Error.FAILED.getCode())
                .setErrMsg(Error.FAILED.getMessage());
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
        }
    }

    /**
     * <pre>
     *获取策略管理详情
     * </pre>
     */
    @Override
    public void getAuditManagementById(AuditManagementRequest request, StreamObserver<AuditManagementQueryReply> responseObserver) {
        AuditManagementQueryReply.Builder builder = AuditManagementQueryReply.newBuilder();
        AuditManagementQueryReply reply;
        try{
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "l")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/audit/getAuditManagementById/{id}}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), request.getToken());
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = auditManagementsService.getAuditManagementById(request.getId());
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }catch (Exception e){
            logger.error(e.getMessage(), e);
            builder.setErrCode(Error.FAILED.getCode())
                .setErrMsg(Error.FAILED.getMessage());
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
        }
    }
    /**
     * <pre>
     *定时登出
     * </pre>
     */
    @Override
    public void timeLoginOut(OutRequest request,
                             StreamObserver<CommonReply> responseObserver) {
        CommonReply.Builder builder = CommonReply.newBuilder();
        try {
            String token = request.getToken();
            String refresh = request.getRefresh();
            if (tokenManager.checkToken(token, refresh) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                //全局控制鉴权判空
            } else if (!validation(token)) {
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
            } else {
                tokenManager.removeToken(request);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        builder.setErrCode(Error.SUCCESS.getCode()).setErrMsg(Error.SUCCESS.getMessage());
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    //20版本前后端交互没用到
    @Override
    public void saveSafeToPy(AddSafePyRequest request,
                             StreamObserver<CommonReply> responseObserver) {
        CommonReply.Builder builder = CommonReply.newBuilder();
        CommonReply reply;
        try {
            reply = safeService.insertSysSafeBusinessToPy(request);
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            builder.setErrCode(Error.FAILED.getCode())
                .setErrMsg(Error.FAILED.getMessage());
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
        }
    }


    /**
     * <pre>
     *前端记录安全审计数据
     * </pre>
     */
    @Override
    public void saveSafe(AddSafeRequest request,
                         StreamObserver<CommonReply> responseObserver) {
        CommonReply.Builder builder = CommonReply.newBuilder();
        CommonReply reply;
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
                //全局控制鉴权判空
            } else if (!validation(token)) {
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = safeService.insertSysSafeBusiness(request);
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            builder.setErrCode(Error.SUCCESS.getCode())
                .setErrMsg(Error.SUCCESS.getMessage());
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
        }
    }

    /**
     * <pre>
     * 更新异常审计推送结果
     * </pre>
     */
    @Override
    public void updateExceptionPush(SafeDTORequest request,
                                    StreamObserver<SafeDTOReply> responseObserver) {
        SafeDTOReply.Builder builder = SafeDTOReply.newBuilder();
        SafeDTOReply reply;
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "i")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/safe/updatePush}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), request.getToken());
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = safeService.updateExcePush(request);
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            builder.setErrCode(Error.SUCCESS.getCode()).setErrMsg(Error.SUCCESS.getMessage());
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
        }
    }

    /**
     * <pre>
     * 查询有异常的安全审计
     * </pre>
     */
    @Override
    public void queryExceptionSafes(SafeDTORequest request,
                                    StreamObserver<SafeDTOReply> responseObserver) {
        SafeDTOReply.Builder builder = SafeDTOReply.newBuilder();
        SafeDTOReply reply;
        try {
            String refresh = request.getRefresh();
            String token = request.getToken();
            if (tokenManager.checkToken(token, refresh) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "i")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{v2/powermaster/safe/queryExcs}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), request.getToken());
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = safeService.queryExceptionSafes(request);
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
        }
    }

    /**
     * <pre>
     * 获取安全审计数据
     * </pre>
     */
    @Override
    public void querySafes(SafeAuditRequest request,
                           StreamObserver<SafeAuditReply> responseObserver) {
        SafeAuditReply.Builder builder = SafeAuditReply.newBuilder();
        SafeAuditReply reply;
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "i") && !validation(token, "m")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/safe/querySafes}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), request.getToken());
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = safeService.querySafes(request);

            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage());
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
        }
    }

    /**
     * <pre>
     *导入安全审计数据
     * </pre>
     */
    @Override
    public void importSafes(ImportSafeRequest request,
                            StreamObserver<ImportSafeReply> responseObserver) {
        ImportSafeReply.Builder builder = ImportSafeReply.newBuilder();
        ImportSafeReply reply;
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "i")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/safe/import}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), request.getToken());
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = safeService.importSafes(request);
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage());
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
        }
    }

    /**
     * <pre>
     *导出安全审计数据
     * </pre>
     */
    @Override
    public void outputSafes(SafeAuditRequest request,
                            StreamObserver<SafeAuditReply> responseObserver) {
        SafeAuditReply.Builder builder = SafeAuditReply.newBuilder();
        SafeAuditReply reply;
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "i")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/safe/output}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), request.getToken());
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = safeService.outputSafes(request);
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage());
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
        }
    }

    /**
     * <pre>
     *安全审计报表
     * </pre>
     */
    @Override
    public void reportSafes(SafeDTORequest request,
                            StreamObserver<ReportSafeReply> responseObserver) {
        ReportSafeReply.Builder builder = ReportSafeReply.newBuilder();
        ReportSafeReply reply;
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "k")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/safe/report}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), request.getToken());
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = safeService.reportSafes(request);

                List<SafeDataResult> dataList = reply.getDataList();
                int total = dataList.size();
                Map<Integer, List<SafeDataResult>> pageNum2Content = getCurrentPageNum2Content(dataList, request.getPageSize(), request.getPageNum());
                int pageNum = 0;
                List<SafeDataResult> pageContent = null;
                for (Integer key : pageNum2Content.keySet()) {
                    pageNum = key;
                    pageContent = pageNum2Content.get(key);
                }
                if(pageContent != null){
                    builder.addAllData(pageContent);
                }
                builder.setCurrentPage(pageNum);
                builder.setTotal(total);
                reply = builder.setErrCode(Error.SUCCESS.getCode()).setErrMsg(Error.SUCCESS.getMessage()).build();
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage());
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
        }
    }



    /**
     * 修改 isc邮件告警配置
     */

    @Override
    public void modifyAlertEmailProperties(ModifyAlertEmailPropertiesRequest request,
                                           StreamObserver<ModifyAlertEmailPropertiesReply> responseObserver){
        ModifyAlertEmailPropertiesReply.Builder builder = ModifyAlertEmailPropertiesReply.newBuilder();
        ModifyAlertEmailPropertiesReply reply;
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "j")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/safe/modifyAlertEmailProperties}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), request.getToken());
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = safeService.modifyAlertEmailProperties(request);
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage());
            builder.setErrCode(Error.FAILED.getCode())
                .setErrMsg(Error.FAILED.getMessage());
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
        }
    }


    /**
     * isc邮件告警配置查询
     * @param request
     * @param responseObserver
     */
    @Override
    public void getAlertEmailProperties(AlertEmailPropertiesRequest request,
                                        StreamObserver<AlertEmailPropertiesReply> responseObserver){
        AlertEmailPropertiesReply.Builder builder = AlertEmailPropertiesReply.newBuilder();
        AlertEmailPropertiesReply reply;
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {

                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "j")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/safe/getAlertEmailProperties}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), request.getToken());
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = safeService.getAlertEmailProperties(request);
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage());
            builder.setErrCode(Error.FAILED.getCode())
                .setErrMsg(Error.FAILED.getMessage());
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
        }
    }

    /**
     * <pre>
     * 获取系统容量
     * </pre>
     */
    @Override
    public void getSafeVolume(SafeAuditRequest request,
                              StreamObserver<SafeVolumeReply> responseObserver) {
        SafeVolumeReply.Builder builder = SafeVolumeReply.newBuilder();
        SafeVolumeReply reply;
        try {
            String refresh = request.getRefresh();
            String token = request.getToken();
            if (tokenManager.checkToken(token, refresh) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "i")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/safe/getSafeVolume}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), request.getToken());
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
               reply = safeService.getSafeVolume(request);
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            builder.setErrCode(Error.SUCCESS.getCode());
            builder.setErrMsg(Error.SUCCESS.getMessage());
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
        }
    }
    @Override
    public void getAiTemp(GetAiTempRequest request, StreamObserver<GetAiTempReply> responseObserver) {
        GetAiTempReply reply;
        GetAiTempReply.Builder builder = GetAiTempReply.newBuilder();
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "f")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/ai/temp/current}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), request.getToken());
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = aiDataProvider.getAITemp(request.getNum());
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            reply = builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }
    }
    @Override
    public void getTempHistory(GetTempHistoryRequest request, StreamObserver<GetTempHistoryReply> responseObserver) {
        GetTempHistoryReply reply;
        GetTempHistoryReply.Builder builder = GetTempHistoryReply.newBuilder();
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "f")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/ai/temps}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), request.getToken());
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = aiDataProvider.getTempHistory(request.getStartTime(), request.getEndTime());
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            reply = builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }
    }

    @Override
    public void senior(SeniorRequest request, StreamObserver<SeniorReply> responseObserver) {
        SeniorReply.Builder builder = SeniorReply.newBuilder();
        SeniorReply reply;
        try {
            String refresh = request.getRefresh();
            String token = request.getToken();
            if (tokenManager.checkToken(token, refresh) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "a")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/senior}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), request.getToken());
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = thunderDataProvider.senior();
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            reply = builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }
    }

    /**
     * <pre>
     * 空调型号
     * </pre>
     */
    @Override
    public void getAirTypes(BlankRequest request,
                            StreamObserver<AirTypesReply> responseObserver) {
        AirTypesReply.Builder builder = AirTypesReply.newBuilder();
        AirTypesReply reply;
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "f")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/air/getAirTypes}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), request.getToken());
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = airService.getAirTypes();
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            builder.setErrCode(Error.FAILED.getCode());
            builder.setErrMsg(Error.FAILED.getMessage());
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
        }
    }

    /**
     * 通过主键获取机柜信息
     *
     * @param request
     * @param responseObserver
     */
    @Override
    public void getCabinetsAndServerByDeviceId(QueryCabinetServerRequest request,
                                               StreamObserver<CabinetsAndServerReply> responseObserver) {
        CabinetsAndServerReply.Builder builder = CabinetsAndServerReply.newBuilder();
        CabinetsAndServerReply reply;
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "f")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/server/getCabinetsAndServerByDeviceId}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), request.getToken());
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = serverService.getCabinetTempByDeviceId(request.getDeviceId());
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            builder.setErrCode(Error.FAILED.getCode());
            builder.setErrMsg(Error.FAILED.getMessage());
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
        }
    }

    /**
     * 推荐机柜
     */
    @Override
    public void recommendCabinet(CabinetRequest request,
                                 StreamObserver<RecommendCabinetReply> responseObserver) {
        RecommendCabinetReply.Builder builder = RecommendCabinetReply.newBuilder();
        RecommendCabinetReply reply;
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "f")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/server/getRecommendCabinet}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), request.getToken());
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = serverService.recommendCabinet();
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            builder.setErrCode(Error.FAILED.getCode());
            builder.setErrMsg(Error.FAILED.getMessage());
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
        }
    }



    @Override
    public void getCFDData(AlgorithmsRequest request,
                           StreamObserver<CFDReply> responseObserver) {
        CFDReply.Builder builder = CFDReply.newBuilder();
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
            } else if (!validation(token, "f")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/cfd/getCFDData}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), request.getToken());
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
            } else {
                builder = cfdService.queryCfd(request).toBuilder();
            }

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            builder.setErrCode(Error.FAILED.getCode());
            builder.setErrMsg(Error.FAILED.getMessage());
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    /**
     * <pre>
     *
     * 推荐温度曲线
     * </pre>
     */
    @Override
    public void qyeryRecommendTemps(QueryRecommendTempReply request,
                                    StreamObserver<RecommendTempReply> responseObserver) {
        RecommendTempReply.Builder builder = RecommendTempReply.newBuilder();
        RecommendTempReply reply;
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "f")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/air/qyeryRecommendTemps}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), request.getToken());
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = airService.getRecommendTemps(request);
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            builder.setErrCode(Error.FAILED.getCode());
            builder.setErrMsg(Error.FAILED.getMessage());
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
        }
    }

    /**
     * @Description: 获取推荐温度
     * @Author: zhangshun
     * @Date: 2020/2/21
     */
    @Override
    public void getRecommendTemp(AlgorithmsRequest request,
                                 StreamObserver<RecommendTempReply> responseObserver) {
        RecommendTempReply.Builder builder = RecommendTempReply.newBuilder();
        RecommendTempReply reply;
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "f")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/air/getRecommendTemp}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), request.getToken());
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = airService.getRecommendTempNew();
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            builder.setErrCode(Error.FAILED.getCode());
            builder.setErrMsg(Error.FAILED.getMessage());
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
        }
    }

    @Override
    public void getCabinetsAndServerTemp(CabinetRequest request,
                                         StreamObserver<CabinetsAndServerTempReply> responseObserver) {
        CabinetsAndServerTempReply.Builder builder = CabinetsAndServerTempReply.newBuilder();
        CabinetsAndServerTempReply reply;
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "f")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/server/getCabinetsAndServerTemp}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), request.getToken());
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = serverService.queryCabinetServerTemp();
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            reply = builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }
    }

    @Override
    public void choseLeader(ChoseLeaderRequest request, StreamObserver<ChoseLeaderReply> responseObserver) {
        ChoseLeaderReply.Builder builder = ChoseLeaderReply.newBuilder();
        ChoseLeaderReply reply;
    }

    //20版本前后端交互没用到
    @Override
    public void getNodeData(GetNodeDataRequest request, StreamObserver<GetNodeDataReply> responseObserver) {
        GetNodeDataReply.Builder builder = GetNodeDataReply.newBuilder();
        GetNodeDataReply reply;
        try {
            reply = ZkClientUtil.getNodeData(request.getPath());
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            reply = builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }
    }
    //20版本前后端交互没用到
    @Override
    public void deleteNodeData(DeleteNodeDataRequest request, StreamObserver<DeleteNodeDataReply> responseObserver) {
        DeleteNodeDataReply.Builder builder = DeleteNodeDataReply.newBuilder();
        DeleteNodeDataReply reply;
        try {
            reply = ZkClientUtil.deleteNodeData(request.getPath());
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            reply = builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }
    }


    @Override
    public void getWarnings(WarningRequest request, StreamObserver<GetWarningReply> responseObserver) {
        GetWarningReply.Builder builder = GetWarningReply.newBuilder();
        GetWarningReply reply;
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "h")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/warnings}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), request.getToken());
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                List<WarningData> warnings = warningService.findAll(request.getState());
                int total = warnings.size();
                Map<Integer, List<WarningData>> pageNum2Content = getCurrentPageNum2Content(warnings, request.getPageSize(), request.getPageNum());
                int pageNum = 0;
                List<WarningData> pageContent = new ArrayList<>();
                for (Integer key : pageNum2Content.keySet()) {
                    pageNum = key;
                    pageContent = pageNum2Content.get(key);
                }
                GetWarningReply.Data.Builder builder1 = GetWarningReply.Data.newBuilder();
                builder1.addAllWarnings(pageContent);
                builder1.setCurrentPage(pageNum);
                builder1.setTotal(total);
                reply = builder.setErrCode(Error.SUCCESS.getCode()).setErrMsg(Error.SUCCESS.getMessage())
                    .setData(builder1.build()).build();
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            reply = builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }
    }

    @Override
    public void updateWarningState(UpdateWarningRequest request, StreamObserver<BaseReply> responseObserver) {
        BaseReply.Builder builder = BaseReply.newBuilder();
        BaseReply reply;
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "h")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/warning}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), request.getToken());
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                warningService.update(request);
                reply = builder.setErrCode(Error.SUCCESS.getCode()).setErrMsg(Error.SUCCESS.getMessage()).build();
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            reply = builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }
    }


    @Override
    public void getWarningCount(GetWarningCountRequest request, StreamObserver<GetWarningCountReply> responseObserver) {
        GetWarningCountReply.Builder builder = GetWarningCountReply.newBuilder();
        GetWarningCountReply reply;
        int count = 0;
        try {
            String token = request.getToken();
            String refresh = request.getRefresh();
            if (tokenManager.checkToken(token, refresh) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "h")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/warning/count}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), request.getToken());
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                count = warningService.findWarningCount();
                reply = builder.setErrCode(Error.SUCCESS.getCode()).setErrMsg(Error.SUCCESS.getMessage()).setData(count).build();
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            reply = builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }
    }

    @Override
    public void powerMonitoring(PowerMonitoringRequest request, StreamObserver<PowerMonitoringReply> responseObserver) {
        PowerMonitoringReply.Builder builder = PowerMonitoringReply.newBuilder();
        PowerMonitoringReply reply;
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "h")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/warning/monitoring}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), request.getToken());
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = warningService.powerMonitoring();
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            reply = builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }
    }

    @Override
    public void getServerCount(GetServerCountRequest request, StreamObserver<GetServerCountReply> responseObserver) {
        GetServerCountReply.Builder builder = GetServerCountReply.newBuilder();
        GetServerCountReply reply;
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "h")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/powers}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), request.getToken());
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = aiDataProvider.getServerCount();
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            reply = builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }
    }

    @Override
    public void getLastAiTemp(GetLastAiTempRequest request, StreamObserver<GetAiTempReply> responseObserver) {
        GetAiTempReply reply;
        GetAiTempReply.Builder builder = GetAiTempReply.newBuilder();
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "f")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/ai/temp/last}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), request.getToken());
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = aiDataProvider.getLastAiTemp();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            reply = builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
        }
        responseObserver.onNext(reply);
        responseObserver.onCompleted();
    }

    //20版本前后端交互没用到
    @Override
    public void getAiStrategiesPower(GetAiStrategiesPowerRequest request, StreamObserver<GetAiPowerReply> responseObserver) {
        GetAiPowerReply reply;
        GetAiPowerReply.Builder builder = GetAiPowerReply.newBuilder();
        try {
            reply = aiDataProvider.getAiStrategiesPower(request.getStrategy());
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            reply = builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }
    }

    //20版本前后端交互没用到
    @Override
    public void getAiPower(GetAiPowerRequest request, StreamObserver<GetAiPowerReply> responseObserver) {
        GetAiPowerReply reply;
        GetAiPowerReply.Builder builder = GetAiPowerReply.newBuilder();
        try {
            reply = aiDataProvider.getAiPower();
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            reply = builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }
    }


    @Override
    public void getAiStrategiesPowerHistory(GetAiStrategiesPowerHistoryRequest request, StreamObserver<GetAiStrategiesPowerHistoryReply> responseObserver) {
        GetAiStrategiesPowerHistoryReply reply;
        GetAiStrategiesPowerHistoryReply.Builder builder = GetAiStrategiesPowerHistoryReply.newBuilder();
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "d")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/ai/strategies/powers}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), request.getToken());
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = aiDataProvider.getAiStrategiesPowerHistory(request.getStartTime(), request.getEndTime(), request.getStrategy());
            }

            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            reply = builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }
    }


    //20版本前后端交互没用到
    @Override
    public void getLastAiPower(GetLastAiTempRequest request, StreamObserver<GetAiPowerReply> responseObserver) {
        GetAiPowerReply reply;
        GetAiPowerReply.Builder builder = GetAiPowerReply.newBuilder();
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "k")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/ai/power/last}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), request.getToken());
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = aiDataProvider.getLastAiPower();
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            reply = builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }
    }

    @Override
    public void getAiPowerHistory(GetAiPowerHistoryRequest request, StreamObserver<GetAiPowerHistoryReply> responseObserver) {
        GetAiPowerHistoryReply reply;
        GetAiPowerHistoryReply.Builder builder = GetAiPowerHistoryReply.newBuilder();
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "d")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/ai/powers}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), request.getToken());
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = aiDataProvider.getAiPowerHistory(request.getStartTime(), request.getEndTime());
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            reply = builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }
    }

    //CFD计算
    @Override
    public void getCfdCalculation(GetCfdCalculationRequest request, StreamObserver<GetCfdCalculationReply> responseObserver) {
        GetCfdCalculationReply reply;
        GetCfdCalculationReply.Builder builder = GetCfdCalculationReply.newBuilder();
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "f")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/cfd/calculation}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), request.getToken());
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = aiDataProvider.getCfdCalculation(request);
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            reply = builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }
    }

    //CFD数据增强
    @Override
    public void getCfdDataEnhancement(GetCfdDataEnhancementRequest request, StreamObserver<GetCfdDataEnhancementReply> responseObserver) {
        GetCfdDataEnhancementReply reply;
        GetCfdDataEnhancementReply.Builder builder = GetCfdDataEnhancementReply.newBuilder();
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "f")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/cfd/enhancement}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), request.getToken());
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = aiDataProvider.getCfdDataEnhancement(request);
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            reply = builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }
    }

    @Override
    public void getStrategiesName(GetStrategiesNameRequest request, StreamObserver<GetStrategiesNameReply> responseObserver) {
        GetStrategiesNameReply reply;
        GetStrategiesNameReply.Builder builder = GetStrategiesNameReply.newBuilder();
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "d")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/ai/strategies}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), request.getToken());
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = aiDataProvider.getStrategiesNames();
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            reply = builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }
    }

    //20版本前后端交互没用到
    @Override
    public void getWarningData(GetWarningDataRequest request, StreamObserver<GetWarningDataReply> responseObserver) {
        GetWarningDataReply reply;
        GetWarningDataReply.Builder builder = GetWarningDataReply.newBuilder();
        try {
            reply = thunderDataProvider.getWarningData();
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            reply = builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }
    }

    @Override
    public void getQosCollectInfo(GetQosCollectInfoRequest request, StreamObserver<GetQosCollectInfoReply> responseObserver) {
        GetQosCollectInfoReply reply;
        GetQosCollectInfoReply.Builder builder = GetQosCollectInfoReply.newBuilder();
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "d")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/qosMonitor/info}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = aiDataProvider.getQosCurrent(request.getBusiness());
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            reply = builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }
    }

    @Override
    public void getQosHistoryCollectInfos(GetQosHistoryCollectInfosRequest request, StreamObserver<GetQosHistoryCollectInfosReply> responseObserver) {
        GetQosHistoryCollectInfosReply reply;
        GetQosHistoryCollectInfosReply.Builder builder = GetQosHistoryCollectInfosReply.newBuilder();
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "d")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/qosMonitor/infos}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = aiDataProvider.getQosHistory(request.getBusiness(), request.getStartTime(), request.getEndTime());
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            reply = builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }
    }


    @Override
    public void getQpsAndServerAmount(GetQpsAndServerAmountRequest request, StreamObserver<GetQpsAndServerAmountReply> responseObserver) {
        GetQpsAndServerAmountReply reply;
        GetQpsAndServerAmountReply.Builder builder = GetQpsAndServerAmountReply.newBuilder();
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "o")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/qps/amount}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = energyViewProvider.getQpsAndServerAmount(request.getBusinessIds(), request.getStartTime(), request.getEndTime());
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            reply = builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }
    }

    @Override
    public void getServerPowerAndAirTemp(GetServerPowerAndAirTempRequest request, StreamObserver<GetServerPowerAndAirTempReply> responseObserver) {
        GetServerPowerAndAirTempReply reply;
        GetServerPowerAndAirTempReply.Builder builder = GetServerPowerAndAirTempReply.newBuilder();
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "o")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/device/view}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = energyViewProvider.getServerPowerAndAirTemp(request.getStartTime(), request.getEndTime());
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            reply = builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }
    }

    @Override
    public void getEnergyEfficiencyRatioHistory(GetEnergyEfficiencyRatioHistoryRequest request, StreamObserver<GetEnergyEfficiencyRatioHistoryReply> responseObserver) {
        GetEnergyEfficiencyRatioHistoryReply reply;
        GetEnergyEfficiencyRatioHistoryReply.Builder builder = GetEnergyEfficiencyRatioHistoryReply.newBuilder();
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "o")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/device/view/eer/history}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = energyViewProvider.getEnergyEfficiencyRatioHistory(request.getCycle());
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            reply = builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }
    }

    @Override
    public void getEnergyEfficiencyRatioInfos(GetEnergyEfficiencyRatioInfosRequest request, StreamObserver<GetEnergyEfficiencyRatioInfosReply> responseObserver) {
        GetEnergyEfficiencyRatioInfosReply reply;
        GetEnergyEfficiencyRatioInfosReply.Builder builder = GetEnergyEfficiencyRatioInfosReply.newBuilder();
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "o")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/device/view/eer}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = energyViewProvider.getEnergyEfficiencyRatioInfos();
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            reply = builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }
    }

    @Override
    public void getBusinessServers(GetBusinessServersRequest request, StreamObserver<GetBusinessServersReply> responseObserver) {

        GetBusinessServersReply.Builder builder = GetBusinessServersReply.newBuilder();
        GetBusinessServersReply reply;
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "o")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/device/view/business/servers}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                GetBusinessServersReply businessServersReply = energyViewProvider.getBusinessServers(request.getBusinessId(), request.getStr());
                List<BusinessServer> list = businessServersReply.getData().getBusinessServerListList();
                int total = list.size();
                Map<Integer, List<BusinessServer>> currentPageNum2Content = getCurrentPageNum2Content(list, request.getPageSize(), request.getPageNum());
                int pageNum = 0;
                List<BusinessServer> pageContent = new ArrayList<>();
                for (Integer key : currentPageNum2Content.keySet()) {
                    pageNum = key;
                    pageContent = currentPageNum2Content.get(key);
                }

                BusinessServersData.Builder builder1 = BusinessServersData.newBuilder();
                builder1.addAllBusinessServerList(pageContent);
                builder1.setCurrentPage(pageNum);
                builder1.setTotal(total);
                reply = builder.setData(builder1.build()).build();
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            reply = builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }
    }

    /**
     * 策略管理类
     * @param request
     * @param responseObserver
     */
    @Override
    public void addStrategy(com.aliyun.heiyu.powermaster.proto.AddStrategyRequest request,
                            StreamObserver<com.aliyun.heiyu.powermaster.proto.BaseReply> responseObserver) {
        BaseReply.Builder builder = BaseReply.newBuilder();
        BaseReply reply;
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "e")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/strategies}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else if(isTamper(toSignString(request), request.getSign())){
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg("请求不合法");
                reply = builder.build();
            } else {
                request = decrypt(request);
                if("".equals(request.getSert())){
                    builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg("请求不合法");
                    reply = builder.build();
                } else {
                    reply = strategyService.addStrategy(request);
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            reply = builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
        }
        responseObserver.onNext(reply);
        responseObserver.onCompleted();
    }


    @Override
    public void updateStrategy(com.aliyun.heiyu.powermaster.proto.AddStrategyRequest request,
                               StreamObserver<com.aliyun.heiyu.powermaster.proto.BaseReply> responseObserver) {
        BaseReply.Builder builder = BaseReply.newBuilder();
        BaseReply reply;
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "e")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/strategies/update}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else if(!StringUtil.isEmpty(request.getStrategyName()) && isTamper(toSignString(request), request.getSign())){
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg("请求不合法");
                reply = builder.build();
            } else {
                if(!StringUtil.isEmpty(request.getStrategyName())){
                    request = decrypt(request);
                    if("".equals(request.getSert())){
                        builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg("请求不合法");
                        reply = builder.build();
                    } else {
                        reply = strategyService.updateStrategy(request);
                    }
                } else {
                    reply = strategyService.updateStrategy(request);
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            reply = builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
        }
        responseObserver.onNext(reply);
        responseObserver.onCompleted();
    }

    @Override
    public void removeStrategy(com.aliyun.heiyu.powermaster.proto.RemoveStrategyRequest request,
                               StreamObserver<com.aliyun.heiyu.powermaster.proto.BaseReply> responseObserver) {
        BaseReply.Builder builder = BaseReply.newBuilder();
        BaseReply reply;
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "e")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/strategies/remove}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = strategyService.removeStrategy(request);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            reply = builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
        }
        responseObserver.onNext(reply);
        responseObserver.onCompleted();
    }

    @Override
    public void getStrategies(com.aliyun.heiyu.powermaster.proto.GetStrategiesRequest request,
                              StreamObserver<com.aliyun.heiyu.powermaster.proto.GetStrategiesReply> responseObserver) {
        GetStrategiesReply.Builder builder = GetStrategiesReply.newBuilder();
        GetStrategiesReply reply;
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "e")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/strategies}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = strategyService.getStrategies(request);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            reply = builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
        }
        responseObserver.onNext(reply);
        responseObserver.onCompleted();
    }

    @Override
    public void getAirSiteBasal(GetAirSiteBasalRequest request,
                              StreamObserver<GetAirSiteBasalReply> responseObserver) {
        GetAirSiteBasalReply.Builder builder = GetAirSiteBasalReply.newBuilder();
        GetAirSiteBasalReply reply;
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "e") && !validation(token, "f")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/models/airSiteBasal}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = aiDataProvider.getAirSiteBasal(request);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            reply = builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
        }
        responseObserver.onNext(reply);
        responseObserver.onCompleted();
    }


    @Override
    public void getStrategyDetail(com.aliyun.heiyu.powermaster.proto.GetStrategyDetailRequest request,
                                  StreamObserver<com.aliyun.heiyu.powermaster.proto.GetStrategyDetailReply> responseObserver) {
        GetStrategyDetailReply.Builder builder = GetStrategyDetailReply.newBuilder();
        GetStrategyDetailReply reply;
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "e")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/strategies/{id}}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                StrategyDetail strategy = strategyService.getStrategyDetail(request.getId());
                GetStrategyDetailReply.Data.Builder builder1 = GetStrategyDetailReply.Data.newBuilder();
                if (strategy != null) {
                    builder1.setStrategy(strategy);
                }
                reply = builder.setErrCode(Error.SUCCESS.getCode()).setErrMsg(Error.SUCCESS.getMessage()).setData(builder1.build()).build();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            reply = builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
        }
        responseObserver.onNext(reply);
        responseObserver.onCompleted();
    }

    @Override
    public void addDeviceInStrategy(com.aliyun.heiyu.powermaster.proto.AddDeviceInStrategyRequest request,
                                    StreamObserver<com.aliyun.heiyu.powermaster.proto.BaseReply> responseObserver) {
        BaseReply.Builder builder = BaseReply.newBuilder();
        BaseReply reply;
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "e") && !validation(token, "b") && !validation(token, "c")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/strategies/{id}/devices}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = strategyService.updateDevicesInStrategy(request);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            reply = builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
        }
        responseObserver.onNext(reply);
        responseObserver.onCompleted();
    }

    @Override
    public void removeDeviceInStrategy(com.aliyun.heiyu.powermaster.proto.RemoveDeviceInStrategyRequest request,
                                       StreamObserver<com.aliyun.heiyu.powermaster.proto.BaseReply> responseObserver) {
        BaseReply.Builder builder = BaseReply.newBuilder();
        BaseReply reply;
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "e")) {
               StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/strategies/devices/remove}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = strategyService.removeDeviceInStrategy(request);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            reply = builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
        }
        responseObserver.onNext(reply);
        responseObserver.onCompleted();
    }

    @Override
    public void getStrategyControlHistory(com.aliyun.heiyu.powermaster.proto.GetStrategyControlHistoryRequest request,
                                          StreamObserver<com.aliyun.heiyu.powermaster.proto.GetStrategyControlHistoryReply> responseObserver) {
        GetStrategyControlHistoryReply.Builder builder = GetStrategyControlHistoryReply.newBuilder();
        GetStrategyControlHistoryReply reply;
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "e") && !validation(token, "b") && !validation(token, "c")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/strategies/devices/{deviceId}/controlHistory}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = strategyService.getStrategyControlHistory(request);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            reply = builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
        }
        responseObserver.onNext(reply);
        responseObserver.onCompleted();
    }

    @Override
    public void getStrategyControlSurvey(GetStrategyControlSurveyRequest request,
                                         StreamObserver<com.aliyun.heiyu.powermaster.proto.GetStrategyControlSurveyReply> responseObserver) {
        GetStrategyControlSurveyReply.Builder builder = GetStrategyControlSurveyReply.newBuilder();
        GetStrategyControlSurveyReply reply;
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "d") && !validation(token, "e")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/strategies/devices/controlSurvey}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                GetStrategyControlSurveyReply.Data data = strategyService.getStrategyControlSurvey();
                builder.setErrCode(Error.SUCCESS.getCode()).setErrMsg(Error.SUCCESS.getMessage()).setData(data);
                reply = builder.build();
            }
        } catch (Exception e) {
            reply = builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
            logger.error(e.getMessage(), e);
        }
        responseObserver.onNext(reply);
        responseObserver.onCompleted();
    }

    @Override
    public void addDeviceInStrategyCheck(com.aliyun.heiyu.powermaster.proto.AddDeviceInStrategyCheckRequest request,
                                         StreamObserver<com.aliyun.heiyu.powermaster.proto.AddDeviceInStrategyCheckReply> responseObserver) {
        AddDeviceInStrategyCheckReply.Builder builder = AddDeviceInStrategyCheckReply.newBuilder();
        AddDeviceInStrategyCheckReply reply;
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "e") && !validation(token, "b") && !validation(token, "c")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/strategies/{id}/devices/{deviceIds}}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                List<String> strings = strategyService.updateDevicesInStrategyCheck(request);
                if (!strings.isEmpty()){
                    AddDeviceInStrategyCheckReply.Data.Builder builder1 = AddDeviceInStrategyCheckReply.Data.newBuilder();
                    for (String string : strings) {
                        builder1.addDeviceIds(string);
                    }

                    reply = builder.setData(builder1).setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
                }else {
                    reply = builder.setErrCode(Error.SUCCESS.getCode()).setErrMsg(Error.SUCCESS.getMessage()).build();
                }

            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            reply = builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }
    }



    /**
     * 设备管理类
     * @param request
     * @param responseObserver
     */

    @Override
    public void addDevice(com.aliyun.heiyu.powermaster.proto.AddDeviceRequest request,
                          StreamObserver<com.aliyun.heiyu.powermaster.proto.AddDeviceReply> responseObserver) {
        AddDeviceReply.Builder builder = AddDeviceReply.newBuilder();
        try {
            String token = request.getDevice().getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
            } else if (!validation(token, "b") && !validation(token, "c") && !validation(token, "e")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/devices}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
            } else {
                builder = powerDataService.insert(request);
            }
        } catch (Exception e) {
            builder = builder.setErrCode(DeviceErrorEnum.SYSTEM_ERROR.getCode()).setErrMsg(DeviceErrorEnum.SYSTEM_ERROR.getMsg());
            logger.error(e.getMessage(), e);
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    @Override
    public void updateDevice(com.aliyun.heiyu.powermaster.proto.UpdateDeviceRequest request,
                             StreamObserver<com.aliyun.heiyu.powermaster.proto.UpdateDeviceReply> responseObserver) {
        UpdateDeviceReply.Builder builder = UpdateDeviceReply.newBuilder();
        try {
            String token = request.getDevice().getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
            } else if (!validation(token, "b") && !validation(token, "c") && !validation(token, "e")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/devices/update}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
            } else {
                builder = powerDataService.update(request);
            }
        } catch (Exception e) {
            builder = builder.setErrCode(DeviceErrorEnum.SYSTEM_ERROR.getCode()).setErrMsg(DeviceErrorEnum.SYSTEM_ERROR.getMsg());
            logger.error(e.getMessage(), e);
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    @Override
    public void deleteDevice(com.aliyun.heiyu.powermaster.proto.DeleteDeviceRequest request,
                             StreamObserver<com.aliyun.heiyu.powermaster.proto.DeleteDeviceReply> responseObserver) {
        DeleteDeviceReply.Builder builder = DeleteDeviceReply.newBuilder();
        String deviceSn = request.getDeviceSn();
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
            } else if (!validation(token, "b") && !validation(token, "c") && !validation(token, "e")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/devices/remove}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
            } else {
                builder = powerDataService.delete(deviceSn);
            }
        } catch (Exception e) {
            builder = builder.setErrCode(DeviceErrorEnum.SYSTEM_ERROR.getCode()).setErrMsg(DeviceErrorEnum.SYSTEM_ERROR.getMsg());
            logger.error(e.getMessage(), e);
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }

    @Override
    public void exportDevices(com.aliyun.heiyu.powermaster.proto.ExportDevicesRequest request,
                              io.grpc.stub.StreamObserver<com.aliyun.heiyu.powermaster.proto.ExportDevicesReply> responseObserver) {
        ExportDevicesReply.Builder builder = ExportDevicesReply.newBuilder();
        ExportDevicesReply reply;
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "b") && !validation(token, "e") && !validation(token, "c")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/devicedetails}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = powerDataService.exportDeviceList(request);
            }

        } catch (Exception e) {
            reply = builder.setErrCode(DeviceErrorEnum.SYSTEM_ERROR.getCode()).setErrMsg(DeviceErrorEnum.SYSTEM_ERROR.getMsg()).build();
            logger.error(e.getMessage(), e);
        }
        responseObserver.onNext(reply);
        responseObserver.onCompleted();
    }

    @Override
    public void importDevices(com.aliyun.heiyu.powermaster.proto.ImportDevicesRequest request,
                              io.grpc.stub.StreamObserver<com.aliyun.heiyu.powermaster.proto.ImportDevicesReply> responseObserver) {
        ImportDevicesReply.Builder builder = ImportDevicesReply.newBuilder();
        ImportDevicesReply reply;
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "b") && !validation(token, "c") && !validation(token, "e")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/devicedetails}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = powerDataService.importDeviceList(request);
            }

        } catch (Exception e) {
            builder = ImportDevicesReply.newBuilder()
                .setErrCode(DeviceErrorEnum.SYSTEM_ERROR.getCode()).setErrMsg(DeviceErrorEnum.SYSTEM_ERROR.getMsg());
            reply = builder.build();
            logger.error(e.getMessage(), e);
        }
        responseObserver.onNext(reply);
        responseObserver.onCompleted();
    }

    @Override
    public void getDevices(com.aliyun.heiyu.powermaster.proto.GetDevicesRequest request,
                           StreamObserver<com.aliyun.heiyu.powermaster.proto.GetDevicesReply> responseObserver) {
        GetDevicesReply.Builder builder = GetDevicesReply.newBuilder();
        GetDevicesReply reply;
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "b") && !validation(token, "c") && !validation(token, "e")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/devices}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = powerDataService.getDeviceList(request);
            }
        } catch (Exception e) {
            reply = builder.setErrCode(DeviceErrorEnum.SYSTEM_ERROR.getCode()).setErrMsg(DeviceErrorEnum.SYSTEM_ERROR.getMsg()).build();
            logger.error(e.getMessage(), e);
        }
        responseObserver.onNext(reply);
        responseObserver.onCompleted();
    }
    
    @Override
    public void getDeviceSns(com.aliyun.heiyu.powermaster.proto.GetDeviceSnsRequest request,
                             StreamObserver<com.aliyun.heiyu.powermaster.proto.GetDeviceSnsReply> responseObserver) {
        GetDeviceSnsReply.Builder builder = GetDeviceSnsReply.newBuilder();
        GetDeviceSnsReply reply;
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "b") && !validation(token, "c") && !validation(token, "e") && !validation(token, "g")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/device/sns}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = powerDataService.getDeviceSns(request.getType());
            }
        } catch (Exception e) {
            reply = builder.setErrCode(DeviceErrorEnum.SYSTEM_ERROR.getCode()).setErrMsg(DeviceErrorEnum.SYSTEM_ERROR.getMsg()).build();
            logger.error(e.getMessage(), e);
        }
        responseObserver.onNext(reply);
        responseObserver.onCompleted();
    }


    @Override
    public void getDeviceDetail(com.aliyun.heiyu.powermaster.proto.GetDeviceDetailRequest request,
                                StreamObserver<com.aliyun.heiyu.powermaster.proto.GetDeviceDetailReply> responseObserver) {
        GetDeviceDetailReply.Builder builder = GetDeviceDetailReply.newBuilder();
        GetDeviceDetailReply reply;
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "b") && !validation(token, "c") && !validation(token, "e")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/devices/{device_sn}}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = powerDataService.getDeviceDetail(request);
            }
        } catch (Exception e) {
            reply = builder.setErrCode(DeviceErrorEnum.SYSTEM_ERROR.getCode()).setErrMsg(DeviceErrorEnum.SYSTEM_ERROR.getMsg()).build();
            logger.error(e.getMessage(), e);
        }
        responseObserver.onNext(reply);
        responseObserver.onCompleted();
    }

    /**
     * <pre>
     * 设备动态数据
     * </pre>
     */
    @Override
    public void dynamicDevice(DynamicDeviceRequest request,
                              StreamObserver<DeviceDynamicReply> responseObserver) {
        DeviceDynamicReply.Builder builder = DeviceDynamicReply.newBuilder();
        DeviceDynamicReply reply;
        try {
            String refresh = request.getRefresh();
            String token = request.getToken();
            if (tokenManager.checkToken(token, refresh) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "b") && !validation(token, "c") && !validation(token, "e")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/devices/denamic/{device_sn}}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = powerDataService.dynamicDetail(request);
            }
        } catch (Exception e) {
            reply = builder.setErrCode(DeviceErrorEnum.SYSTEM_ERROR.getCode()).setErrMsg(DeviceErrorEnum.SYSTEM_ERROR.getMsg()).build();
            logger.error(e.getMessage(), e);
        }
        responseObserver.onNext(reply);
        responseObserver.onCompleted();
    }

    @Override
    public void getPowerInfo(com.aliyun.heiyu.powermaster.proto.GetPowerInfoRequest request,
                             StreamObserver<com.aliyun.heiyu.powermaster.proto.GetPowerInfoReply> responseObserver) {
        GetPowerInfoReply.Builder builder = GetPowerInfoReply.newBuilder();
        GetPowerInfoReply reply;
        String label = request.getLabel();
        String startTime = request.getStartTime();
        String endTime = request.getEndTime();
        int interval = request.getInterval();
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "b") && !validation(token, "a")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/power}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = powerDataService.getPower(label, startTime, endTime, interval);
            }
        } catch (Exception e) {
            reply = builder.setErrCode(DeviceErrorEnum.SYSTEM_ERROR.getCode()).setErrMsg(DeviceErrorEnum.SYSTEM_ERROR.getMsg()).build();
            logger.error(e.getMessage(), e);
        }
        responseObserver.onNext(reply);
        responseObserver.onCompleted();
    }

    @Override
    public void getStatistics(com.aliyun.heiyu.powermaster.proto.GetStatisticsRequest request,
                              StreamObserver<com.aliyun.heiyu.powermaster.proto.GetStatisticsReply> responseObserver) {
        GetStatisticsReply.Builder builder = GetStatisticsReply.newBuilder();
        GetStatisticsReply reply;
        try {
            String refresh = request.getRefresh();
            String token = request.getToken();
            if (tokenManager.checkToken(token, refresh) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "a")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/statistics}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = powerDataService.getStatistics();
            }
        } catch (Exception e) {
            reply = builder.setErrCode(DeviceErrorEnum.SYSTEM_ERROR.getCode()).setErrMsg(DeviceErrorEnum.SYSTEM_ERROR.getMsg()).build();
            logger.error(e.getMessage(), e);
        }
        responseObserver.onNext(reply);
        responseObserver.onCompleted();
    }

    @Override
    public void getCappingFreq1(com.aliyun.heiyu.powermaster.proto.GetCappingFreq1Request request,
                                StreamObserver<com.aliyun.heiyu.powermaster.proto.GetCappingFreq1Reply> responseObserver) {
        GetCappingFreq1Reply.Builder builder = GetCappingFreq1Reply.newBuilder();
        GetCappingFreq1Reply reply;
        String deviceSn = request.getDeviceSn();
        String startTime = request.getStartTime();
        String endTime = request.getEndTime();
        int interval = request.getInterval();
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
            } else if (!validation(token, "a")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/cappingfreqs/{device_sn}}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
            } else {
                builder = powerDataService.getcapFreq(deviceSn, startTime, endTime, interval);
            }

            reply = builder.build();
        } catch (Exception e) {
            reply = builder.setErrCode(DeviceErrorEnum.SYSTEM_ERROR.getCode()).setErrMsg(DeviceErrorEnum.SYSTEM_ERROR.getMsg()).build();
            logger.error(e.getMessage(), e);
        }
        responseObserver.onNext(reply);
        responseObserver.onCompleted();
    }

    @Override
    public void updateDeviceDynamic(com.aliyun.heiyu.powermaster.proto.UpdateDeviceDynamicRequest request,
                                    StreamObserver<com.aliyun.heiyu.powermaster.proto.UpdateDeviceDynamicReply> responseObserver) {
        UpdateDeviceDynamicReply.Builder builder = UpdateDeviceDynamicReply.newBuilder();
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
            } else if (!validation(token, "b")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/devices/dynamic/update}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
            } else {
                builder = powerDataService.updateDynamic(request);
            }
        } catch (Exception e) {
            builder = builder.setErrCode(DeviceErrorEnum.SYSTEM_ERROR.getCode()).setErrMsg(DeviceErrorEnum.SYSTEM_ERROR.getMsg());
            logger.error(e.getMessage(), e);
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }


    //20版本前后端没有交互
    @Override
    public void getServerInfo(com.aliyun.heiyu.powermaster.proto.GetServerInfoRequest request,
                              StreamObserver<com.aliyun.heiyu.powermaster.proto.GetServerInfoReply> responseObserver) {
        String fields = request.getFields();
        GetServerInfoReply serverInfos = thunderDataProvider.getServerInfos(fields);
        responseObserver.onNext(serverInfos);
        responseObserver.onCompleted();
    }


    @Override
    public void updateJdbcStatus(UpdateJdbcStatusRequest request, StreamObserver<UpdateJdbcStatusReply> responseObserver) {
        UpdateJdbcStatusReply.Builder builder = UpdateJdbcStatusReply.newBuilder();
        UpdateJdbcStatusReply reply;
        try {
            String token = request.getToken();
            int code = tokenManager.checkToken(token);
            if (code != 0) {
                reply = builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg()).build();
            } else if (!validation(token, "y")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/jdbc/status}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = builder.setErrCode(Error.SUCCESS.getCode()).setErrMsg(Error.SUCCESS.getMessage()).build();
            }
        } catch (Exception e) {
            reply = builder.setErrCode(DeviceErrorEnum.SYSTEM_ERROR.getCode()).setErrMsg(DeviceErrorEnum.SYSTEM_ERROR.getMsg()).build();
            logger.error(e.getMessage(), e);
        }
        responseObserver.onNext(reply);
        responseObserver.onCompleted();
    }


    @Override
    public void getJdbcStatus(GetJdbcStatusRequest request, StreamObserver<UpdateJdbcStatusReply> responseObserver) {
        UpdateJdbcStatusReply.Builder builder = UpdateJdbcStatusReply.newBuilder();
        UpdateJdbcStatusReply reply;
        try {
            String token = request.getToken();
            int code = tokenManager.checkToken(token);
            if (code != 0) {
                reply = builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg()).build();
            }  else if (!validation(token, "y")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/jdbc/status}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), request.getToken());
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                boolean status = true;
                //boolean status = ConnectionManager.getInstance().getJdbcStatus();
                reply = builder.setJdbcStatus(status).setErrCode(Error.SUCCESS.getCode()).setErrMsg(Error.SUCCESS.getMessage()).build();
            }
        } catch (Exception e) {
            reply = builder.setErrCode(DeviceErrorEnum.SYSTEM_ERROR.getCode()).setErrMsg(DeviceErrorEnum.SYSTEM_ERROR.getMsg()).build();
            logger.error(e.getMessage(), e);
        }
        responseObserver.onNext(reply);
        responseObserver.onCompleted();
    }

    @Override
    public void getModelInference(GetModelInferenceRequest request, StreamObserver<GetModelInferenceReply> responseObserver) {
        GetModelInferenceReply.Builder builder = GetModelInferenceReply.newBuilder();
        GetModelInferenceReply reply;
        try {
            request = decrypt(request);
            String sert = request.getSert();
            String token = request.getToken();
            int code = tokenManager.checkToken(token);
            if (code != 0) {
                reply = builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg()).build();
            }  else if (!validation(token, "g")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/ai/models/inference}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else if ("".equals(sert)){
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg("请求不合法");
                reply = builder.build();
            } else {
                reply = aiDataProvider.getModelInference(request.getTaskId(),request.getData());
                reply = encrypt(reply , sert);
            }
        } catch (Exception e) {
            reply = builder.setErrCode(DeviceErrorEnum.SYSTEM_ERROR.getCode()).setErrMsg(DeviceErrorEnum.SYSTEM_ERROR.getMsg()).build();
            logger.error(e.getMessage(), e);
        }
        responseObserver.onNext(reply);
        responseObserver.onCompleted();
    }

    //电科院测试 -- 数据库适配
    public void databaseConnect(DatabaseConnectRequest request, StreamObserver<BaseReply> responseObserver) {
        BaseReply.Builder builder = BaseReply.newBuilder();
        BaseReply reply;
        String token = request.getToken();
        try {
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "q")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/database/connection}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                if(isTamper(toSignString(request), request.getSign())){
                    builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg("请求不合法");
                    reply = builder.build();
                } else {
                    request = decrypt(request);
                    if("".equals(request.getSert())){
                        builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg("请求不合法");
                        reply = builder.build();
                    } else {
                        reply = operaService.insert(request);
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            reply = builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
        }
        responseObserver.onNext(reply);
        responseObserver.onCompleted();
    }
    public void removeDatabaseConnect(RemoveDatabaseConnectRequest request, StreamObserver<BaseReply> responseObserver) {
        BaseReply.Builder builder = BaseReply.newBuilder();
        BaseReply reply;
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "q")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/database/connection/remove}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = operaService.delete(request);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            reply = builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
        }
        responseObserver.onNext(reply);
        responseObserver.onCompleted();
    }


    public void getDataBaseConnections(EmptRequest request, StreamObserver<ConnectionReply> responseObserver) {
        ConnectionReply.Builder builder = ConnectionReply.newBuilder();
        ConnectionReply reply;
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "q")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/database/connection}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = operaService.getConnections1();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            reply = builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
        }
        responseObserver.onNext(reply);
        responseObserver.onCompleted();
    }

    public void getData(GetDataRequest request, StreamObserver<GetDataReply> responseObserver) {
        GetDataReply.Builder builder = GetDataReply.newBuilder();
        GetDataReply reply;
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "q")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/database/data}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = operaService.getData(request);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            reply = builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
        }
        responseObserver.onNext(reply);
        responseObserver.onCompleted();
    }

    @Override
    public void mysqlDateConvert(MysqlDateConvertRequest request, StreamObserver<MysqlDateConvertReply> responseObserver) {
        MysqlDateConvertReply.Builder builder = MysqlDateConvertReply.newBuilder();
        MysqlDateConvertReply reply;
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "q")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/mysql/data/convert}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                String result = operaService.convertData(request.getTag(), request.getParam());
                builder.setErrCode(Error.SUCCESS.getCode()).setErrMsg(Error.SUCCESS.getMessage());
                reply = builder.setData(MysqlDateConvertReply.Data.newBuilder().setResult(result)).build();
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            reply = builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }
    }


    @Override
    public void databaseBackupTime(DatabaseBackupTimeRequest request, StreamObserver<DatabaseBackupTimeReply> responseObserver) {
        DatabaseBackupTimeReply.Builder builder = DatabaseBackupTimeReply.newBuilder();
        DatabaseBackupTimeReply reply;
        try {
            String token = request.getToken();
            int code = tokenManager.checkToken(token);
            if (code != 0) {
                reply = builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg()).build();
            } else if (!validation(token, "v")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/properties/database/time}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                propertiesService.databaseBackupTime(request);
                reply = builder.setErrCode(Error.SUCCESS.getCode()).setErrMsg(Error.SUCCESS.getMessage()).build();
            }
        } catch (Exception e) {
            reply = builder.setErrCode(DeviceErrorEnum.SYSTEM_ERROR.getCode()).setErrMsg(DeviceErrorEnum.SYSTEM_ERROR.getMsg()).build();
            logger.error(e.getMessage(), e);
        }
        responseObserver.onNext(reply);
        responseObserver.onCompleted();
    }


    @Override
    public void getDatabaseBackupTime(GetDatabaseBackupTimeRequest request, StreamObserver<GetDatabaseBackupTimeReply> responseObserver) {
        GetDatabaseBackupTimeReply.Builder builder = GetDatabaseBackupTimeReply.newBuilder();
        GetDatabaseBackupTimeReply reply;
        try {
            request = decrypt(request);
            String sert = request.getSert();
            String token = request.getToken();
            int code = tokenManager.checkToken(token);
            if (code != 0) {
                reply = builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg()).build();
            } else if (!validation(token, "v")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/properties/database/time}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else if ("".equals(sert)){
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg("请求不合法");
                reply = builder.build();
            } else {
                reply = propertiesService.getDatabaseBackupData();
                reply = encrypt(reply, sert);
            }
        } catch (Exception e) {
            reply = builder.setErrCode(DeviceErrorEnum.SYSTEM_ERROR.getCode()).setErrMsg(DeviceErrorEnum.SYSTEM_ERROR.getMsg()).build();
            logger.error(e.getMessage(), e);
        }
        responseObserver.onNext(reply);
        responseObserver.onCompleted();
    }

    //告警级别修改
    @Override
    public void updateAlarmLevel(UpdateAlarmLevelRequest request, StreamObserver<UpdateAlarmLevelReply> responseObserver) {
        UpdateAlarmLevelReply.Builder builder = UpdateAlarmLevelReply.newBuilder();
        UpdateAlarmLevelReply reply;
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "u")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/warning/level}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = warningService.updateAlarmLevel(request);
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            reply = builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }
    }

    //告警级别查看
    @Override
    public void getAlarmLevel(GetAlarmLevelRequest request, StreamObserver<GetAlarmLevelReply> responseObserver) {
        GetAlarmLevelReply.Builder builder = GetAlarmLevelReply.newBuilder();
        GetAlarmLevelReply reply;
        try {
            String token = request.getToken();
            if (tokenManager.checkToken(token) != 0) {
                builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg());
                reply = builder.build();
            } else if (!validation(token, "u")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/warning/level}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                reply = warningService.getAlarmLevel(request);
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            reply = builder.setErrCode(Error.FAILED.getCode()).setErrMsg(Error.FAILED.getMessage()).build();
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }
    }

    @Override
    public void getLogConfig(GetLogConfigRequest request, StreamObserver<GetLogConfigReply> responseObserver) {
        GetLogConfigReply.Builder builder = GetLogConfigReply.newBuilder();
        GetLogConfigReply reply;
        try {
            String token = request.getToken();
            int code = tokenManager.checkToken(token);
            if (code != 0) {
                reply = builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg()).build();
            } else if (!validation(token, "u")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/properties/getLogConfig}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                UpdateLogRequest logConfig = propertiesService.getLogConfig();
                if (!ObjectUtils.isEmpty(logConfig)) {
                    GetLogConfigReply.Data.Builder builder1 = GetLogConfigReply.Data.newBuilder();
                    builder1.setLogConfig(logConfig);
                    builder.setData(builder1.build());
                }
                reply = builder.build();
            }
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        } catch (Exception e) {
            reply = builder.setErrCode(DeviceErrorEnum.SYSTEM_ERROR.getCode()).setErrMsg(DeviceErrorEnum.SYSTEM_ERROR.getMsg()).build();
            logger.error(e.getMessage(), e);
        }
        responseObserver.onNext(reply);
        responseObserver.onCompleted();
    }


    @Override
    public void updateLogConfig(UpdateLogRequest request, StreamObserver<UpdateLogReply> responseObserver) {
        UpdateLogReply.Builder builder = UpdateLogReply.newBuilder();
        UpdateLogReply reply;
        try {
            String token = request.getToken();
            int code = tokenManager.checkToken(token);
            if (code != 0) {
                reply = builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg()).build();
            } else if (!validation(token, "u")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/properties/log}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                propertiesService.updateLogConfig(request);
                reply = builder.setErrCode(Error.SUCCESS.getCode()).setErrMsg(Error.SUCCESS.getMessage()).build();
            }
        } catch (Exception e) {
            reply = builder.setErrCode(DeviceErrorEnum.SYSTEM_ERROR.getCode()).setErrMsg(DeviceErrorEnum.SYSTEM_ERROR.getMsg()).build();
            logger.error(e.getMessage(), e);
        }
        responseObserver.onNext(reply);
        responseObserver.onCompleted();
    }

    @Override
    public void updateLogEnvironment(UpdateLogEnvironmentRequest request, StreamObserver<UpdateLogEnvironmentReply> responseObserver) {
        UpdateLogEnvironmentReply.Builder builder = UpdateLogEnvironmentReply.newBuilder();
        UpdateLogEnvironmentReply reply;
        try {
            String token = request.getToken();
            int code = tokenManager.checkToken(token);
            if (code != 0) {
                reply = builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg()).build();
            } else if (!validation(token, "s")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/properties/logConfig/environment}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                propertiesService.updateLogEnvironment(request);
                reply = builder.setErrCode(Error.SUCCESS.getCode()).setErrMsg(Error.SUCCESS.getMessage()).build();
            }
        } catch (Exception e) {
            reply = builder.setErrCode(DeviceErrorEnum.SYSTEM_ERROR.getCode()).setErrMsg(DeviceErrorEnum.SYSTEM_ERROR.getMsg()).build();
            logger.error(e.getMessage(), e);
        }
        responseObserver.onNext(reply);
        responseObserver.onCompleted();
    }

    @Override
    public void getLogEnvironment(GetLogEnvironmentRequest request, StreamObserver<GetLogEnvironmentReply> responseObserver) {
        GetLogEnvironmentReply.Builder builder = GetLogEnvironmentReply.newBuilder();
        GetLogEnvironmentReply reply;
        try {
            String token = request.getToken();
            int code = tokenManager.checkToken(token);
            if (code != 0) {
                reply = builder.setErrCode(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getCode()).setErrMsg(UserErrorEnum.USER_INVALID_TOKEN_ERROR.getMsg()).build();
            } else if (!validation(token, "s")) {
                StringBuilder str = new StringBuilder();
                str.append("在时间[")
                    .append(DateUtil.dateToString(new Date()))
                    .append("]")
                    .append("越权访问了-{/v2/powermaster/properties/logenvironment/status}");
                safeService.insertSysSafeSystemException(new SysSafeAuditEntity(str.toString()), token);
                builder.setErrCode(Error.VALIDATE_FAILED.getCode()).setErrMsg(Error.VALIDATE_FAILED.getMessage());
                reply = builder.build();
            } else {
                int status = propertiesService.getLogEnvironment();
                reply = builder.setStatus(status).setErrCode(Error.SUCCESS.getCode()).setErrMsg(Error.SUCCESS.getMessage()).build();
            }
        } catch (Exception e) {
            reply = builder.setErrCode(DeviceErrorEnum.SYSTEM_ERROR.getCode()).setErrMsg(DeviceErrorEnum.SYSTEM_ERROR.getMsg()).build();
            logger.error(e.getMessage(), e);
        }
        responseObserver.onNext(reply);
        responseObserver.onCompleted();
    }

    @Override
    public void kubernetesManager(KubernetesManagerRequest request, StreamObserver<BaseReply> responseObserver) {
        BaseReply.Builder builder = BaseReply.newBuilder();
        GetLogEnvironmentReply reply;
        try {
            int action = request.getAction();
            String err = "";
            if(1 == action){
                err = k8sManager.addNode(request.getMasterIp(),request.getNodeIp());
            } else if(2 == action){
                err = k8sManager.deleteNode(request.getMasterIp(),request.getNodeHostname(),request.getNodeIp());
            } else if(3 == action){
                err = k8sManager.cordonNode(request.getMasterIp(),request.getNodeHostname());
            } else if(4 == action){
                err = k8sManager.uncordonNode(request.getMasterIp(),request.getNodeHostname());
            } else {
                err = "action 参数错误，请重新操作";
            }
            if("success".equals(err)){
                builder.setErrCode(DeviceErrorEnum.SUCCESS.getCode()).setErrMsg(DeviceErrorEnum.SUCCESS.getMsg());
            } else {
                builder.setErrCode(DeviceErrorEnum.SYSTEM_ERROR.getCode()).setErrMsg(err);
            }
        } catch (Exception e) {
            builder.setErrCode(DeviceErrorEnum.SYSTEM_ERROR.getCode()).setErrMsg(DeviceErrorEnum.SYSTEM_ERROR.getMsg());
            logger.error(e.getMessage(), e);
        }
        responseObserver.onNext(builder.build());
        responseObserver.onCompleted();
    }


    /**
     * 返回指定页的内容  pageSize: 一页显示的条数， pageNum: 页码，从1开始，1代表第一页
     */
    private <T> Map<Integer, List<T>> getCurrentPageNum2Content(List<T> list, int pageSize, int pageNum) {
        if (pageSize < 0 || pageNum < 0) {
            throw new IllegalArgumentException("wrong argument: pageSize:" + pageSize + ",pageNum:" + pageNum);
        }
        Map<Integer, List<T>> ret = new HashMap<>();
        if (list == null) {
            list = new ArrayList<>();
        }
        if (list.size() == 0) {
            ret.put(1, list);
            return ret;
        }
        //如果不传pageSize或pageNum，则返回全部列表，当前页为1
        if (pageSize == 0 || pageNum == 0) {
            ret.put(1, list);
            return ret;
        }
        //智能分页指针定位
        int size = list.size();
        int start = (pageNum - 1) * pageSize;//start Index: include
        while (start >= size) {
            pageNum--;
            start -= pageSize;
        }
        int end = start + pageSize;//end index : exclude
        if (end > size) {
            end = size;
        }
        ret.put(pageNum, list.subList(start, end));
        return ret;
    }

    //越权访问校验
    private boolean validation(String token, String res){
        if("market_token".equals(token)){
            return true;
        }
        if (StringUtil.isEmpty(token)) {
            logger.debug("请求涉及越权访问，token为空");
            return false;
        }
        Map<String, String> result = tokenMangerDao.findByToken(token);
        if (null == result || result.size() == 0) {
            logger.debug("请求涉及越权访问，找不到token对应数据，token = {}", token);
            return false;
        }
        String resources = result.get("resources");
        if (StringUtil.isEmpty(resources)) {
            logger.debug("请求涉及越权访问，找不到对应资源数据，resources = {}", resources);
            return false;
        }
        String decode = "";
        try {
            decode = SM4Util.decrypt_CBC2(resources);
            if (!decode.contains(res)) {
                logger.debug("请求涉及越权访问，没有对应权限资源访问，resources = {}, res = {}", decode,res);
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug("越权访问异常捕获, msg = {}",e.getMessage());
            return false;
        }

        return true;
    }

    //越权访问全局接口校验
    private boolean validation(String token){
        if (StringUtil.isEmpty(token)) {
            logger.debug("请求涉及越权访问，token为空");
            return false;
        }
        Map<String, String> result = tokenMangerDao.findByToken(token);
        if (null == result || result.size() == 0) {
            logger.debug("请求涉及越权访问，找不到token对应数据，token = {}", token);
            return false;
        }
        String resources = result.get("resources");
        if (StringUtil.isEmpty(resources)) {
            logger.debug("请求涉及越权访问，找不到对应资源数据，resources = {}", resources);
            return false;
        }
        return true;
    }

    public boolean isTamper(String orSign, String reSign){
        //请求是否合法
        boolean b = !reSign.equalsIgnoreCase(orSign);
        return b;
    }

    private String decodeSM4(String data, String sert){
        String[] split = sert.split(",");
        //SM4_CBC模式
        String s = SM4Util.decrypt_CBC2_tran(data, split[0], split[1]);
        return s;
    }

    private String encodeSM4(String data, String sert){
        String[] split = sert.split(",");
        //SM4_CBC模式
        return SM4Util.encrypt_CBC2_tran(data, split[0], split[1]);
    }

    public String decodeSM2(String param) {
        if(StringUtil.isEmpty(param) || !param.contains(",")){
            return "";
        }
        StringBuffer buffer = new StringBuffer();
        String[] split = param.split(",");
        if(split.length != 2){
            return "";
        }
        buffer.append(SM2Util.decryptToHex(split[0]));
        buffer.append(",");
        buffer.append(SM2Util.decryptToHex(split[1]));

        return buffer.toString();
    }

    public String toSignString(AddStrategyRequest request){
        JsonArray jsonArray = new JsonArray();
        List<StrategyAction> strategyActionsList = request.getStrategyActionsList();
        if(strategyActionsList == null || strategyActionsList.size() == 0){
            //return "";
            String s = new GsonBuilder().disableHtmlEscaping().create().toJson(jsonArray);
            return SM3Util.convertEncryption(s);
        }
        int type = request.getType();
        for(StrategyAction strategyAction : strategyActionsList){
            JsonObject actionObject = new JsonObject();
            JsonObject conditionObject = new JsonObject();
            if(2 == type){
                StrategyAction.ActionCondition actionCondition = strategyAction.getActionCondition();
                conditionObject.addProperty("endTime",actionCondition.getEndTime());
                conditionObject.addProperty("maxCPUUsage",actionCondition.getMaxCPUUsage());
                conditionObject.addProperty("maxPower",actionCondition.getMaxPower());
                conditionObject.addProperty("minCPUUsage",actionCondition.getMinCPUUsage());
                conditionObject.addProperty("minPower",actionCondition.getMinPower());
                conditionObject.addProperty("startTime",actionCondition.getStartTime());
            }
            actionObject.add("actionCondition",conditionObject);
            actionObject.addProperty("actionName",strategyAction.getActionName());
            actionObject.addProperty("actionState",strategyAction.getActionState());
            actionObject.addProperty("capTo",strategyAction.getCapTo());
            actionObject.addProperty("capType",strategyAction.getCapType());
            actionObject.addProperty("fmin",strategyAction.getFmin());
            jsonArray.add(actionObject);
        }
        String s = new GsonBuilder().disableHtmlEscaping().create().toJson(jsonArray);
        return SM3Util.convertEncryption(s);
    }

    public String toSignString(DatabaseConnectRequest request){
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("host",request.getHost());
        jsonObject.addProperty("name",request.getName());
        jsonObject.addProperty("password",request.getPassword());
        jsonObject.addProperty("port",request.getPort());
        jsonObject.addProperty("sert",request.getSert());
        jsonObject.addProperty("type",request.getType());
        jsonObject.addProperty("username",request.getUsername());
        GsonBuilder gsonBuilder = new GsonBuilder().disableHtmlEscaping();
        String s = gsonBuilder.create().toJson(jsonObject);
        return SM3Util.convertEncryption(s);
    }

    public AddStrategyRequest decrypt(AddStrategyRequest request) {
        AddStrategyRequest.Builder builder = request.toBuilder();
        String sert = request.getSert();
        sert= decodeSM2(sert);
        builder.setSert(sert);
        List<StrategyAction> strategyActionsList = request.getStrategyActionsList();
        if(strategyActionsList == null || strategyActionsList.size() == 0){
            return builder.build();
        }
        int type = request.getType();
        ArrayList<StrategyAction> list = new ArrayList<>();
        for(StrategyAction strategyAction : strategyActionsList){
            StrategyAction.Builder builder1 = StrategyAction.newBuilder();
            builder1.setActionName(decodeSM4(strategyAction.getActionName(),sert));
            builder1.setActionState(decodeSM4(strategyAction.getActionState(),sert));
            builder1.setCapTo(decodeSM4(strategyAction.getCapTo(),sert));
            builder1.setCapType(decodeSM4(strategyAction.getCapType(),sert));
            builder1.setFmin(decodeSM4(strategyAction.getFmin(),sert));
            if(2 == type){
                StrategyAction.ActionCondition actionCondition = strategyAction.getActionCondition();
                StrategyAction.ActionCondition.Builder builder2 = StrategyAction.ActionCondition.newBuilder();
                builder2.setStartTime(decodeSM4(actionCondition.getStartTime(),sert));
                builder2.setEndTime(decodeSM4(actionCondition.getEndTime(),sert));
                builder2.setMaxCPUUsage(decodeSM4(actionCondition.getMaxCPUUsage(),sert));
                builder2.setMinCPUUsage(decodeSM4(actionCondition.getMinCPUUsage(),sert));
                builder2.setMaxPower(decodeSM4(actionCondition.getMaxPower(),sert));
                builder2.setMinPower(decodeSM4(actionCondition.getMinPower(),sert));
                builder1.setActionCondition(builder2.build());
            }
            list.add(builder1.build());
        }
        return builder.clearStrategyActions().addAllStrategyActions(list).build();
    }

    public GetModelInferenceRequest decrypt(GetModelInferenceRequest request){
        GetModelInferenceRequest.Builder builder = request.toBuilder();
        String sert = request.getSert();
        sert = decodeSM2(sert);
        return builder.setSert(sert).build();
    }

    public GetDatabaseBackupTimeRequest decrypt(GetDatabaseBackupTimeRequest request){
        GetDatabaseBackupTimeRequest.Builder builder = request.toBuilder();
        String sert = request.getSert();
        builder.setSert(decodeSM2(sert));
        return builder.build();
    }

    public DatabaseConnectRequest decrypt(DatabaseConnectRequest request){
        DatabaseConnectRequest.Builder builder = request.toBuilder();
        String sert = request.getSert();
        sert= decodeSM2(sert);
        builder.setSert(sert);
        builder.setName(decodeSM4(request.getName(), sert));
        builder.setHost(decodeSM4(request.getHost(),sert));
        builder.setUsername(decodeSM4(request.getUsername(),sert));
        builder.setPort(decodeSM4(request.getPort(),sert));
        builder.setPassword(decodeSM4(request.getPassword(),sert));
        builder.setType(decodeSM4(request.getType(),sert));
        return builder.build();
    }

    public GetModelInferenceReply encrypt(GetModelInferenceReply reply, String sert) throws IOException {
        int errCode = reply.getErrCode();
        if(errCode != 0){
            return reply;
        }
        GetModelInferenceReply.Data data = reply.getData();
        if(data == null){
            return reply;
        }
        List<String> inferencesList = data.getInferencesList();
        ArrayList<String> newList = new ArrayList<>();
        if(inferencesList == null){
            return reply;
        }
        for(String s : inferencesList){
            s = encodeSM4(s,sert);
            newList.add(s);
        }
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        String s1 = gson.toJson(newList);
        String sign = SM3Util.convertEncryption(s1);
        data = data.toBuilder().setSign(sign).clearInferences().addAllInferences(newList).build();
        return reply.toBuilder().setData(data).build();
    }

    public GetDatabaseBackupTimeReply encrypt(GetDatabaseBackupTimeReply reply, String sert) {
        String backUpPrivileges = reply.getBackUpPrivileges();
        String name = reply.getName();
        GetDatabaseBackupTimeReply.Builder builder = reply.toBuilder();
        backUpPrivileges = encodeSM4(backUpPrivileges, sert);
        name = encodeSM4(name, sert);
        builder.setBackUpPrivileges(backUpPrivileges);
        builder.setName(name);
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(backUpPrivileges);
        stringBuffer.append(",");
        stringBuffer.append(name);
        String s = stringBuffer.toString();
        builder.setSign(SM3Util.convertEncryption(s));
        return builder.build();
    }
    
}
